<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <div class="list">
        <el-row>
          <el-col :span="2">
            <div class="add">
              <el-button @click="toOpenAddDialog('addRoleRef')" type="primary">
                <i class="el-icon-user"></i>
                添加
              </el-button>
            </div>
          </el-col>

          <el-col :span="22">
            <el-tooltip content="点击刷新" placement="top" effect="dark">
              <el-button
                @click="refreshTable"
                class="refresh"
                type="success"
                icon="el-icon-refresh"
                circle
              ></el-button>
            </el-tooltip>
          </el-col>
        </el-row>

        <el-table
          highlight-current-row
          :data="roleList"
          stripe
          border
          style="width: 1100px "
          header-align="center"
          @selection-change="handleSelectionChange"
        >
          >
          <el-table-column align="center" prop="roleId" width="180" label="ID"></el-table-column>
          <el-table-column
            align="center"
            resizable
            sortable
            prop="roleName"
            label="角色名称"
            width="140"
          >
            <template slot-scope="scope">
              <i class="el-icon-user"></i>
              <span>{{ scope.row.roleName }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="roleDesc" align="center" label="角色描述" width="300"></el-table-column>
          <el-table-column align="center" prop="gmtCreate" sortable label="添加时间" width="190">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.gmtCreate }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center" fixed="right" label="操作" width="230px">
            <template slot-scope="scope">
              <el-button
                class="edit"
                size="mini"
                type="success"
                @click="distributePermissionList(scope.$index, scope.row)"
                :disabled="scope.row.roleName== 'super-admin' ? true : false "
              >分配权限</el-button>
              <el-button
                class="edit"
                size="mini"
                type="success"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button>
              <el-popconfirm
                @confirm="isconfirm( scope.row)"
                confirm-button-text="我意已决"
                cancel-button-text="点错了"
                icon="el-icon-info"
                icon-color="red"
                title="确定要删除吗"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  type="danger"
                  :disabled="scope.row.roleName== 'super-admin' ? true : false "
                >删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 40, 80]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 用户修改对话框 -->

    <div class="dialog-form">
      <el-dialog
        @close="closeDialog"
        title="修改信息"
        :visible="dialogFormVisible"
        width="35%"
        :before-close="handleClose"
      >
        <el-form
          :rules="rules"
          ref="ruleForm"
          label-position="right"
          :model="roleForm"
          label-width="80px"
        >
          <el-form-item disable prop="roleName" label="角色名称">
            <el-input
              :disabled="true"
              clearable
              v-model="roleForm.roleName"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="roleDesc" label="角色描述">
            <el-input
              clearable
              type="textarea"
              :rows="4"
              v-model="roleForm.roleDesc"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateRole('ruleForm')">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 分配权限对话框 -->
    <div class="dialog-form">
      <el-dialog
        @close="closeDialog"
        title="分配权限"
        :visible="distributionDialog"
        width="35%"
        :before-close="handleDistributeClose"
      >
        <el-button type="success" size="mini" @click="selectAllButton">全选</el-button>
        <el-button type="primary" size="mini" @click="resetAll">清空</el-button>

        <el-tree
          :data="treeData"
          ref="tree"
          default-expand-all
          :props="defaultProps"
          show-checkbox
          node-key="psId"
          :default-checked-keys="checkedArray"
          @node-click="handleNodeClick"
        ></el-tree>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateRolePermissionList()">确 定</el-button>
          <el-button @click="distributionDialog = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 角色添加 -->
    <div class="dialog-form">
      <el-dialog
        modal
        top="20px"
        @close="closeDialog"
        title="角色添加"
        :visible="addDialogVisible"
        width="35%"
        :before-close="handleClose"
      >
        <el-form
          label-position="right"
          :rules="rules"
          ref="addMyRoleRef"
          :model="roleForm"
          label-width="80px"
        >
          <el-form-item prop="roleName" label="名称">
            <el-input clearable v-model="roleForm.roleName" class="form-input" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item prop="roleLevel" label="角色">
            <el-select filterable clearable v-model="roleForm.roleLevel" placeholder="请选择角色">
              <el-option label="教师" value="1"></el-option>
              <el-option label="超级管理员" value="0"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="roleDesc" label="描述">
            <el-input
              clearable
              type="textarea"
              :rows="3"
              v-model="roleForm.roleDesc"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addRole('addMyRoleRef')">确 定</el-button>
          <el-button @click="addDialogVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  name: "ManagerList",
  data() {
    return {
      roleList: [], //总记录数
      roleForm: {},
      currentPage: 1, //当前页
      limit: 5, //每页显示多少条
      total: 100, //总条数
      dialogFormVisible: false,
      addDialogVisible: false,
      distributionDialog: false,
      formLabelWidth: "100px",
      multipleSelection: [],
      rules: {
        roleName: [
          {
            required: true,
            message: "角色名称不能为空",
            trigger: "blur"
          }
        ],
        roleDesc: [
          {
            required: true,
            message: "描述不能为空",
            trigger: "blur"
          }
        ],
        roleLevel: [
          { required: true, message: "角色选择不能为空", trigger: "blur" }
        ]
      },
      treeData: [
        {
          psId: 1001,
          psName: "一级 1",
          permissionList: [
            {
              psId: 1002,
              psName: "二级 1"
            }
          ]
        }
      ],
      defaultProps: {
        children: "permissionList",
        label: "psName"
      },
      // 选中的数组[206, 207]
      checkedArray: [],
      roleId: 0
    };
  },
  methods: {
    deleteRole(row) {
      console.log(row.roleId);
    },
    selectAllButton() {
      this.$http
        .get("/manager/permission/noAuthorize/queryAllPermissionList")
        .then(resp => {
          let { msg, code } = resp.data;
          let { permissionVoList } = resp.data.data;
          if (code === 1) {
            permissionVoList.forEach(p => {
              this.checkedArray.push(p.psId);
            });
          } else {
            return this.$message.info(msg);
          }
        });
      this.$refs.tree.setCheckedKeys([]);
    },
    resetAll() {
      this.$refs.tree.setCheckedKeys([]);
    },
    handleNodeClick(data) {
      console.log(data);
    },
    updateRole(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        // 根据角色id修改用户信息
        this.$http
          .put("/manager/role/updateRoleInfo", this.roleForm)
          .then(resp => {
            console.log(resp);
            let { code, msg } = resp.data;
            if (code == 1) {
              this.$message.success(msg);
            } else {
              this.$message.error(msg);
            }
            this.dialogFormVisible = false;
          })
          .catch(resp => {});
      });
    },
    getRoleList() {
      this.$http
        .get("/manager/role/noAuthorize/getRoleListPage", {
          params: {
            page: this.currentPage,
            limit: this.limit
          }
        })
        .then(resp => {
          let { code } = resp.data;
          let { pageResult } = resp.data.data;

          if (code === 1) {
            this.roleList = pageResult.list;
            this.currentPage = pageResult.currPage;
            this.limit = pageResult.pageSize;
            this.total = pageResult.totalCount;
          }
          return this.$message.error(msg);
        })
        .catch(resp => {});
    },

    batchDelete() {
      let ids = [];
      this.multipleSelection.forEach(element => {
        ids.push(element.mgId);
      });
      console.log(ids);
      this.$http
        .delete("/manager/manager/batchDelete", {
          params: {
            ids: ids.toString()
          }
        })
        .then(resp => {
          let { code, msg } = resp.data;
          if (code === 1) {
            this.$message.success("批量删除成功");
            return this.reloadTable();
          }
          return this.$message.error(msg);
        })
        .catch(resp => {});
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    toOpenAddDialog() {
      this.addDialogVisible = true;
    },

    addRole(addRoleRef) {
      this.$refs[addRoleRef].validate(valid => {
        if (valid) {
          this.$http
            .post("/manager/role/addRole", this.roleForm)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code === 1) {
                this.addDialogVisible = false;
                this.$message.success("添加成功");
              } else {
                this.$message.error(msg);
              }
              this.$refs[addRoleRef].resetFields();
            })
            .catch(resp => {});
        }
      });
    },
    distributePermissionList(index, row) {
      this.checkedArray = [];
      this.getAllPermissionList();
      let roleId = row.roleId;
      this.roleId = roleId;
      this.$http
        .get(
          "/manager/permission/noAuthorize/queryPermissionLevel01And02ByRole",
          {
            params: {
              roleId: roleId
            }
          }
        )
        .then(resp => {
          let { msg, code } = resp.data.data;
          let { idList } = resp.data.data;
          this.checkedArray = idList;
        });
    },

    getAllPermissionList() {
      this.$http
        .get("/manager/permission/noAuthorize/queryAllPermissionList")
        .then(resp => {
          let { msg, code } = resp.data;
          let { permissionVoList } = resp.data.data;
          if (code === 1) {
            this.treeData = permissionVoList;
            this.distributionDialog = true;
          } else {
            return this.$message.info(msg);
          }
        });
    },
    updateRolePermissionList() {
      let psIdStr = this.$refs.tree.getCheckedKeys().toString();
      let params = new URLSearchParams();
      params.append("psIdStr", psIdStr);
      params.append("roleId", this.roleId);
      this.$http
        .put("/manager/rp/updateRolePermissionList", params)
        .then(resp => {
          let { msg, code } = resp.data;
          if (code === 1) {
            this.$message.success(msg);
            return (this.distributionDialog = false);
          }
        })
        .catch(resp => {
          let { msg, code } = resp;
          if (code === 204) {
            this.$message.info(msg);
          }
          this.distributionDialog = false;
        });
    },
    handleEdit(index, row) {
      this.roleForm = row;
      this.dialogFormVisible = true;
    },
    isconfirm(row) {
      this.$http
        .delete("/manager/role/deleteRoleByRoleId/" + row.roleId)
        .then(resp => {
          let code = resp.data.code;
          if (code === 1) {
            this.$message({
              showClose: true,
              message: "删除成功！",
              type: "success"
            });
            this.reload();
          } else {
            return this.$message({
              showClose: true,
              message: resp.data.msg,
              type: "warning"
            });
          }
        })
        .catch(resp => {
          console.log(resp);
        });
    },

    handleSizeChange(val) {
      this.limit = val;
      this.getRoleList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getRoleList();
    },
    refreshTable() {
      this.reload();
      this.$message.success("已刷新");
    },
    handleDistributeClose(done) {
      this.$confirm("确认关闭？")
        .then(resp => {
          this.getRoleList();
          this.distributionDialog = false;
          done();
        })
        .catch(resp => {
          this.getRoleList();
        });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(resp => {
          this.getRoleList();
          this.dialogFormVisible = false;
          this.addDialogVisible = false;
          done();
        })
        .catch(resp => {
          this.getRoleList();
        });
    },
    closeDialog() {
      this.getRoleList();
    }
  },
  created() {
    this.getRoleList();
  }
};
</script>

<style scoped>
.el-input {
  width: 150px;
  margin-right: 10px;
}
.list {
  margin-top: 25px;
  margin-left: 20px;
}
.el-row {
  margin-top: 10px;
  margin-bottom: 10px;
}
.refresh {
  float: right;
  margin-right: 20px;
}
.el-pagination {
  margin-top: 10px;
}
.form-input {
  width: 200px;
}
.el-form {
  margin-left: 30px;
}
.el-card {
  margin-top: 20px;
}
.el-breadcrumb {
  margin-top: 10px;
}

.dialog-form {
  margin-top: 20px;
}
.batchdelete {
  margin-left: 38px;
}
.edit {
  float: left;
}
.el-input,
.el-textarea {
  width: 217px;
}
</style>